﻿using Microsoft.AspNetCore.Mvc;
 

namespace 断线续传.Controllers
{
    [ApiController]
    [ Route("[controller]")]
    public class DocumentController : ControllerBase
    {
        public DocumentController()
        {
          
        }
        private  string SourceFilePath= AppDomain.CurrentDomain.BaseDirectory + "Documents/CentOS-7-x86_64-DVD-2207-02.zip";

        [HttpGet("download")]
        public IActionResult Download()
        {
            // 检查是否支持断点续传
            bool isResumable = Request.Headers.TryGetValue("Range", out var rangeHeader) && rangeHeader.ToString().StartsWith("bytes=");

            // 获取文件名
            string fileName = Path.GetFileName(SourceFilePath);

            // 打开文件流
            using (FileStream sourceStream = new FileStream(SourceFilePath, FileMode.Open, FileAccess.Read))
            {
                long fileLength = sourceStream.Length;
                if (isResumable)
                {
                 
                    // 设置响应头部
                    Response.Headers.Add("Accept-Ranges", "bytes");
                    Response.Headers.Add("Content-Disposition", $"attachment; filename=\"{fileName}\"");
                    // 获取起始位置和结束位置
                    (long start, long end) = ParseRange(rangeHeader.ToString(), fileLength);
                    Console.WriteLine($"断点续传,{start}-{end}");
                    // 设置响应码和内容区间
                    Response.StatusCode = 206; // Partial Content
                    Response.Headers.Add("Content-Range", $"bytes {start}-{end}/{fileLength}");

                    // 设置响应流的起始位置
                    sourceStream.Seek(start, SeekOrigin.Begin);

                    // 设置响应内容的长度
                    long contentLength = end - start + 1;
                    Response.ContentLength = contentLength;

                    // 将文件内容写入响应流
                    var buffer = new byte[4096];
                    int bytesRead;
                    while (contentLength > 0 && (bytesRead = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        Response.Body.WriteAsync(buffer, 0, (int)Math.Min(contentLength, bytesRead));
                        contentLength -= bytesRead;
                    }
                }
                else
                {
                    // 设置响应码和内容长度
                    //Response.StatusCode = 200; // OK
                    //Response.ContentLength = fileLength;

                    //// 将整个文件写入响应流
                    //// sourceStream.CopyTo(Response.Body);
                    //byte[] buff = new byte[fileLength];
                    //sourceStream.Read(buff, 0, buff.Length);
                    //Response.Body.WriteAsync(buff);
                 
                    //string fileCategory = data["FileCategory"].ToString();
                    var fileType = "";
                    if (fileName.LastIndexOf('.') > -1)
                    {
                        fileType = fileName.Substring(fileName.LastIndexOf('.'));
                    }
                    new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider()
                       .Mappings.TryGetValue(fileType, out var contentType);

                    FileStream fs = new FileStream(SourceFilePath, FileMode.Open, FileAccess.Read);

                    return File(fs, contentType, fileName, enableRangeProcessing: false); //enableRangeProcessing 是否启动断点续传
                }
            }

            return new EmptyResult();
        }

        private (long, long) ParseRange(string rangeHeader, long fileLength)
        {
            string[] rangeValues = rangeHeader.Replace("bytes=", "").Split('-');
            long start = long.Parse(rangeValues[0]);
            long end = rangeValues[1] != "" ? long.Parse(rangeValues[1]) : fileLength - 1;
            return (start, end);
        }





    }
}
